/*
 * Subsets
Given a set of distinct integers, S, return all possible subsets.

Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]
 */
package com.xinpan.exercise;

import java.util.ArrayList;
import java.util.Arrays;

public class SubSets {
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ArrayList<ArrayList<Integer>> res = new 
            ArrayList<ArrayList<Integer>>();
        
        int[] mask = new int[S.length];
        for(int i = 0; i < S.length; i++)
            mask[i] = 0;
        Arrays.sort(S);
        subSetsHelper(mask, 0, res, S);
        return res;
    }
    
    public void subSetsHelper(int[] mask, int i, ArrayList<ArrayList<Integer>> res,
                                int[] S)
    {
        if(i == mask.length)
        {
            ArrayList<Integer> aRes = new ArrayList<Integer>();
            for(int j = 0; j < mask.length; j++)
            {
                if(mask[j] == 1)
                    aRes.add(S[j]);
            }
            res.add(aRes);
            return;
        }
        
        mask[i] = 0;
        subSetsHelper(mask, i+1, res, S);
        mask[i] = 1;
        subSetsHelper(mask, i+1, res, S);
    }
}
